package cn.community.system.service.impl;

import cn.community.system.domain.Association;
import cn.community.system.domain.Department;
import cn.community.system.domain.Member;
import cn.community.system.domain.MemberVo;
import cn.community.system.exception.LogicException;
import cn.community.system.mapper.*;
import cn.community.system.query.MemberQuery;
import cn.community.system.query.QueryObject;
import cn.community.system.service.IMemberService;
import cn.community.system.util.AssertUtils;
import cn.community.system.util.UploadUtil;
import cn.community.system.util.UserContext;
import cn.community.system.vo.AssoMemberVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class MemberServiceImpl implements IMemberService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private AssociationMapper associationMapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private MemberVoMapper memberVoMapper;

    @Override
    public void delete(Long id) {
         memberMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Long save(Member member) {
        // 加密
        String password = member.getPassword();
        Md5Hash md5Hash = new Md5Hash(password, member.getUsername());
        member.setPassword(md5Hash.toString());
        member.setDegisteTime(new Date());
        return memberMapper.insert(member);
    }

    @Override
    public Member get(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Member> listAll() {
        return memberMapper.selectAll();
    }

    @Override
    public void update(Member member) {
        memberMapper.updateByPrimaryKey(member);
    }

    @Override
    public void myUpdate(Member member) {
        String password = member.getPassword();
        String number = member.getNumber();
        AssertUtils.hasLength(number,"学号不能为空！");
        AssertUtils.hasLength(member.getUsername(),"姓名不能为空！");
        AssertUtils.hasLength(password,"密码不能为空！");
        Member mem = memberMapper.selectByPrimaryKey(member.getId());
        // 密码加密
        if(!mem.getPassword().equals(password)){ // 密码改变时才加密
            Md5Hash md5Hash = new Md5Hash(password, number);
            member.setPassword(md5Hash.toString());
        }
        // 检查手机号是否存在
        String phone = member.getMobile();
        AssertUtils.hasLength(phone,"联系方式不能为空！");
        String mobile = mem.getMobile();
        if(!phone.equals(mobile)){
            if (memberMapper.findByPhone(phone) != null){
                throw new LogicException("该联系方式已被注册！");
            }
        }
        // 图片
        if ("".equals(member.getImgUrl())){
            member.setImgUrl(null);
        }
        System.out.println(member.getImgUrl());
        memberMapper.myUpdate(member);
    }

    @Override
    public void edit(AssoMemberVo assoMemberVo) {
        MemberVo memberVo = new MemberVo();
        memberVo.setMemberId(assoMemberVo.getId());
        memberVo.setPassTime(assoMemberVo.getPassTime());
        memberVo.setIsAgree(assoMemberVo.getIsAgree());
        Long deptId = assoMemberVo.getDeptId();
        memberVo.setDeptId(deptId);
        String name = departmentMapper.selectByPrimaryKey(deptId).getName();
        memberVo.setDeptname(name);
        Association association = UserContext.getCurrentAssociation();
        memberVo.setAssoId(association.getId());
        memberVoMapper.edit(memberVo);
    }

    @Override
    public void updateActivitiesAndTime(Member member) {
        memberMapper.updateActivitiesAndTime(member);
    }

    public PageInfo query(QueryObject qo) {
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<AssoMemberVo> list = memberMapper.selectForList(qo);
        return new PageInfo(list);
    }

    public PageInfo queryByAssoId(MemberQuery qo) {
        Association association = UserContext.getCurrentAssociation();
        qo.setAssoId(association.getId());
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        //查询结果集
        List<AssoMemberVo> list = memberMapper.selectForAssoList(qo);
        return new PageInfo(list);
    }

    @Override
    public boolean checkPhone(String phone) {
        Member member = memberMapper.findByPhone(phone);
        return member != null;
    }

    @Override
    public Long checkAssociation(String association) {
        Long id = associationMapper.findIdByAssociation(association);
        return id;
    }

    @Override
    public Long checkDept(Long id) {
        Long deptId = departmentMapper.findByAssocitionId(id);
        return deptId;
    }

    @Override
    public void regist(Member member,String rpassword) {
        // 1、接收所有的参数进行校验：非空
        AssertUtils.hasLength(member.getNumber(),"学号不能为空！");
        AssertUtils.hasLength(member.getUsername(),"姓名不能为空！");
        AssertUtils.hasLength(member.getPassword(),"密码不能为空！");
        AssertUtils.hasLength(rpassword,"确认密码不能为空！");
        AssertUtils.hasLength(member.getAcademy(),"学院不能为空！");
        AssertUtils.hasLength(member.getMajor(),"专业不能为空！");
        AssertUtils.hasLength(member.getClassName(),"班级不能为空！");
        AssertUtils.hasLength(member.getMobile(),"联系方式不能为空！");
        // 2、校验两次密码是否一致
        AssertUtils.isEqual(member.getPassword(),rpassword,"两次的密码不一致！");
        // 3、手机格式和唯一性的校验
        String regex = "^1[3456789]\\d{9}$";
        if (!member.getMobile().matches(regex)){
            throw new LogicException("手机号码格式不正确！");
        }
        if (this.checkPhone(member.getMobile())){
            throw new LogicException("该手机号已经被注册！");
        }
        // 6、用户注册，将用户信息保存到数据库中
        this.save(member);
    }

    @Override
    public Member userLogin(String username, String password) {
        Member member = memberMapper.selectByNameAndPassword(username, password);
        if (member == null){
            throw new LogicException("账号或密码错误！");
        }
        return member;
    }

    @Override
    public void batchDelete(Long[] ids) {
         memberMapper.deleteBatch(ids);
    }

    // 导入
    @Override
    public void importXls(MultipartFile file) throws Exception {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取行的最大索引数
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 1; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            Member member = new Member();
            member.setNumber(row.getCell(1).getStringCellValue());
            String name = row.getCell(2).getStringCellValue();
            member.setUsername(name);
            member.setPassword(row.getCell(3).getStringCellValue());
            member.setAcademy(row.getCell(4).getStringCellValue());
            member.setMajor(row.getCell(5).getStringCellValue());
            member.setClassName(row.getCell(6).getStringCellValue());
            String sex = row.getCell(7).getStringCellValue();
            member.setSex(sex.charAt(0));
            member.setMobile(row.getCell(8).getStringCellValue());
            member.setEmail(row.getCell(9).getStringCellValue());
            //获取文本格式的单元格内容
            // member.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //获取数值类型的单元格内容
            //double value = row.getCell(2).getNumericCellValue();
            //user.setAge((int)value);
            //调用保存方法
            Long save = this.save(member);

            // 保存关联
            MemberVo memberVo = new MemberVo();
            // 社团
            String assoname = row.getCell(10).getStringCellValue();
            memberVo.setAssoname(assoname);
            Long assoId = associationMapper.selectByName(assoname).getId();
            memberVo.setAssoId(assoId);
            // 部门
            String deptname = row.getCell(11).getStringCellValue();
            memberVo.setDeptname(deptname);
            Department department = departmentMapper.getByAssoIdAndDeptname(assoId, deptname);
            if(department != null){
                memberVo.setDeptId(department.getId());
            }
            // 学生
            Member member1 = memberMapper.getUserByNumber(member.getNumber());
            memberVo.setMemberId(member1.getId());
            memberVo.setName(name);
            memberVo.setIsAgree(MemberVo.AGREE_YES);
            memberVo.setPassTime(new Date());
            memberVoMapper.insert(memberVo);
        }

    }

    // 导出
    @Override
    public Workbook exportXls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet(一页纸)
        Sheet sheet = wb.createSheet("社团成员名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("学号");
        row.createCell(2).setCellValue("姓名");
        row.createCell(3).setCellValue("学院");
        row.createCell(4).setCellValue("专业");
        row.createCell(5).setCellValue("班级");
        row.createCell(6).setCellValue("性别");
        row.createCell(7).setCellValue("联系方式");
        row.createCell(8).setCellValue("邮箱");
        row.createCell(9).setCellValue("所属社团");
        row.createCell(10).setCellValue("所属部门");
        row.createCell(11).setCellValue("入会时间");
        //查询员工数据
        List<AssoMemberVo> members = memberMapper.selectVoAll();
        for (int i = 0; i < members.size(); i++) {
            AssoMemberVo member = members.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(member.getNumber());
            row.createCell(2).setCellValue(member.getUsername());
            row.createCell(3).setCellValue(member.getAcademy());
            row.createCell(4).setCellValue(member.getMajor());
            row.createCell(5).setCellValue(member.getClassName());
            row.createCell(6).setCellValue(member.getSex()+"");
            row.createCell(7).setCellValue(member.getMobile());
            row.createCell(8).setCellValue(member.getEmail());
            row.createCell(9).setCellValue(member.getAssoname());
            row.createCell(10).setCellValue(member.getDeptname());
            Date passTime = member.getPassTime();
            String time = null;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if(passTime != null){
                time = format.format(passTime);
            }
            row.createCell(11).setCellValue(time);
        }
        return wb;
    }

    @Override
    public Workbook exportXls2() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet(一页纸)
        Sheet sheet = wb.createSheet("社团成员名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("序号");
        row.createCell(1).setCellValue("学号");
        row.createCell(2).setCellValue("姓名");
        row.createCell(3).setCellValue("学院");
        row.createCell(4).setCellValue("专业");
        row.createCell(5).setCellValue("班级");
        row.createCell(6).setCellValue("性别");
        row.createCell(7).setCellValue("联系方式");
        row.createCell(8).setCellValue("邮箱");
        row.createCell(9).setCellValue("所属部门");
        row.createCell(10).setCellValue("入会时间");
        //查询员工数据
        Long id = UserContext.getCurrentAssociation().getId();
        List<AssoMemberVo> members = memberMapper.selectVoAll2(id);
        for (int i = 0; i < members.size(); i++) {
            AssoMemberVo member = members.get(i);
            //创建行(每个员工就是一行)
            row = sheet.createRow(i+1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(i+1);
            row.createCell(1).setCellValue(member.getNumber());
            row.createCell(2).setCellValue(member.getUsername());
            row.createCell(3).setCellValue(member.getAcademy());
            row.createCell(4).setCellValue(member.getMajor());
            row.createCell(5).setCellValue(member.getClassName());
            row.createCell(6).setCellValue(member.getSex()+"");
            row.createCell(7).setCellValue(member.getMobile());
            row.createCell(8).setCellValue(member.getEmail());
            row.createCell(9).setCellValue(member.getDeptname());
            Date passTime = member.getPassTime();
            String time = null;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            if(passTime != null){
                time = format.format(passTime);
            }
            row.createCell(10).setCellValue(time);
        }
        return wb;
    }

    @Override
    public Long findIdByName(String applicant) {
        return memberMapper.selectByName(applicant).getId();
    }

    @Override
    public void passOne(Long id,Long assoId,Integer isAgree) {
        // 状态
        memberVoMapper.passOne(id,assoId,isAgree);
        // 入会时间
        if(isAgree == MemberVo.AGREE_YES){
            memberVoMapper.updatePassTime(id,assoId,new Date());
        }else {
            memberVoMapper.updatePassTime(id,assoId,null);
        }
    }

    @Override
    public Member getUserByNumber(String number) {
        return memberMapper.getUserByNumber(number);
    }

}
